package com.imarkket;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.imarkket.Library.c_app_status;
import com.imarkket.Library.c_connection_checking;
import com.imarkket.Library.c_constantes;
import com.imarkket.Library.c_http_post_get;
import com.imarkket.Library.c_logging;
import com.imarkket.Library.c_preferences;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class c_login_activity extends ActionBarActivity {


    static InputStream is				        = null;
    String						ResponseHTTP	= "";

    // Cambiar este dato a 5 o m�s y hacer que sea m�s complicada en base a lo
    // que est� puesto en el PHP.
    private static int			LENGTH_PASSWORD	= 2;

    Integer						ResultTask		= null;

    // Values for email and password at the time of the login attempt.
    private String				mEmail;
    private String				mPassword;
    private String				mRetypePassword;

    private int					pMODO;

    // UI references.
    private EditText mEmailView;
    private EditText			mPasswordView;
    private CheckBox mCheckRemenberView;
    private CheckBox			mCheckAutoLogin;
    private EditText			mRetypePasswordView;
    private Button mButtonRegister;
    protected LoginTask			_Task			= null;

    static Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Inicializamos valores
        this.pMODO = R.string.st_la_Login;

        // Inicializamos la tarea
        this.ResultTask = null;

        c_logging.getInstance().log(c_logging.LOG_INFO, getString(this.pMODO));

        setTitle(getString(R.string.app_name) + " - " + getString(R.string.st_la_Login));

        setContentView(R.layout.l_login);

        // Set up the login form.
        mEmailView = (EditText) findViewById(R.id.email);

        // Restauramos el email por defecto en las preferencias
        Context context = getApplicationContext();
        c_preferences appPrefs = new c_preferences(context);
        mEmailView.setText(appPrefs.getUsername(true));

        // Fin preferencias

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {

                    try {
                        c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Sign_in) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
                        PRC_INTENTAR_LOGIN();
                    } catch (IOException e) {
                        c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Sign_in) + ": (FAIL)" + mEmailView.getText() + "/" + mPasswordView.getText());
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }
        });

        // Quitar esto
        mPasswordView.setText(appPrefs.getPassword(true));

        // Botón de login
        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Sign_in) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
                try {
                    PRC_INTENTAR_LOGIN();
                } catch (IOException e) {
                    c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Sign_in) + ": (FAIL)" + mEmail + "/" + mPasswordView.getText());
                    e.printStackTrace();
                }
            }
        });

        // Preferncia del check
        mCheckRemenberView = (CheckBox) findViewById(R.id.chk_remember);
        mCheckRemenberView.setChecked(appPrefs.getCheckRemenberPref());

        // Preferncia del login
        mCheckAutoLogin = (CheckBox) findViewById(R.id.chk_auto_login);
        mCheckAutoLogin.setChecked(appPrefs.getAutoLogin());

        // Si esta puesto que se auto-loguee, cargo el login
        if (appPrefs.getAutoLogin()) {
            try {
                PRC_INTENTAR_LOGIN();
            } catch (IOException e) {
                c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_auto_login) + ": FAIL");
                e.printStackTrace();
            }
        }

        findViewById(R.id.register_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_register) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
                PRC_INTENTAR_REGISTRO();
            }
        });

        mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
        mRetypePasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {

                    c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_register) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
                    PRC_INTENTAR_REGISTRO();
                    return true;
                }
                return false;
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.m_menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m_la_login_menu_exit:
                c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Exit));
                PRC_INTENTAR_SALIR();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    // Comprobar la validez de un email
    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

    // Recordar mail password con las preferencias
    public void PRC_RECORDAR_MAIL_PASSWORD() {

        Context context = getApplicationContext();
        c_preferences appPrefs = new c_preferences(context);

        if (mCheckRemenberView.isChecked()) {
            // Guardar preferencias
            appPrefs.setUsername(mEmailView.getText().toString());
            appPrefs.setPassword(mPasswordView.getText().toString());
            // Fin preferencias
            // Toast.makeText(LoginActivity.this, "Configuraci�n almacenada",
            // Toast.LENGTH_LONG).show();
        }

        // Siempre guardamos en la preferencia temporal el usuario y el nombre por si no se pincha en recordar tirar de esta preferencia
        appPrefs.setUsernameTemp(mEmailView.getText().toString());
        appPrefs.setPasswordTemp(mPasswordView.getText().toString());

        // Esta preferencia la guardamos siempre
        appPrefs.setCheckRemenberPref(mCheckRemenberView.isChecked());
        appPrefs.setAutoLogin(mCheckAutoLogin.isChecked());
    }

    // Intenta Salir
    public void PRC_INTENTAR_SALIR () {

        // 1. Instantiate an AlertDialog.Builder with its constructor
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        // 2. Chain together various setter methods to set the dialog
        // characteristics
        builder.setMessage(R.string.st_la_pregunta_salir).setTitle(R.string.st_la_Exit);

        builder.setPositiveButton(R.string.st_la_Yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                // Salimos de la herramienta
                c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Exit) + "OK");

                // Si el check est� pinchado recordar en las preferences
                PRC_RECORDAR_MAIL_PASSWORD();

                finish();
            }
        });

        builder.setNegativeButton(R.string.st_la_No, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
                // No hacemos nada
                c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Exit) + "FAIL");
            }
        });

        // 3. Get the AlertDialog from create()
        AlertDialog dialog = builder.create();

        // Mostramos el cuadro de dialogo
        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Exit));
            PRC_INTENTAR_SALIR();
            // Si el listener devuelve true, significa que el evento esta
            // procesado, y nadie debe hacer nada mas
            return true;
        }
        // para las demas cosas, se reenvia el evento al listener habitual
        return super.onKeyDown(keyCode, event);
    }

    // Intento registro
    public void PRC_INTENTAR_REGISTRO() {

        // Si el check está pinchado recordar en las preferences
        PRC_RECORDAR_MAIL_PASSWORD();

        mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
        mButtonRegister = (Button) findViewById(R.id.register_button);

        if (mRetypePasswordView.getVisibility() == View.VISIBLE) {

            boolean cancel = false;
            View focusView = null;

            // Reset errors.
            mEmailView.setError(null);
            mPasswordView.setError(null);
            mRetypePasswordView.setError(null);

            // Store values at the time of the login attempt.
            mEmail = mEmailView.getText().toString();
            mPassword = mPasswordView.getText().toString();
            mRetypePassword = mRetypePasswordView.getText().toString();

            // Check for a valid password.
            if (TextUtils.isEmpty(mPassword)) {
                mPasswordView.setError(getString(R.string.st_la_Field_Required));
                focusView = mPasswordView;
                cancel = true;
            } else if (TextUtils.isEmpty(mRetypePassword)) {
                mRetypePasswordView.setError(getString(R.string.st_la_Field_Required));
                focusView = mRetypePasswordView;
                cancel = true;
            } else if (mPassword.length() < c_login_activity.LENGTH_PASSWORD) {
                mPasswordView.setError(getString(R.string.st_la_Invalid_Password));
                focusView = mPasswordView;
                cancel = true;
            } else if (mRetypePassword.length() < c_login_activity.LENGTH_PASSWORD) {
                mRetypePasswordView.setError(getString(R.string.st_la_Invalid_Password));
                focusView = mRetypePasswordView;
                cancel = true;
            }

            // mPasswordView.setError("*" + mRetypePassword + "-" + mPassword + "*");
            // Check for a valid email address.
            if (TextUtils.isEmpty(mEmail)) {
                mEmailView.setError(getString(R.string.st_la_Field_Required));
                focusView = mEmailView;
                cancel = true;
            } else if (!mEmail.contains("@")) {
                mEmailView.setError(getString(R.string.st_la_Invalid_Email));
                focusView = mEmailView;
                cancel = true;
            } else if (!isValidEmail(mEmail)) {
                mEmailView.setError(getString(R.string.st_la_Email_Error));
                focusView = mEmailView;
                cancel = true;
            } else if (!mPassword.equals(mRetypePassword)) {
                mPasswordView.setError(getString(R.string.st_la_Password_Not_Mistmach));
                focusView = mPasswordView;
                cancel = true;
            }

            if (cancel) {
                // There was an error; don't attempt login and focus the first
                // form field with an error.
                focusView.requestFocus();
                c_logging.getInstance().log(c_logging.LOG_INFO, "Cancelado");
            } else {
                // Show a progress spinner, and kick off a background task to
                // perform the user login attempt.
                // Anulado temporalmente
                // PRC_CARGAR_LOGIN_TASK(context, getString(R.string.st_la_Check_Connection_Thinking), getString(R.string.STR_OPERATION_REGISTER_USER));
            }

        } else {
            mRetypePasswordView.setVisibility(View.VISIBLE);
            mButtonRegister.setText(R.string.st_la_Nuevo);
        }
    }


    public void PRC_INTENTAR_LOGIN () throws IOException {

        // Quitamos los campos de registro de usuario
        mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
        mButtonRegister = (Button) findViewById(R.id.register_button);

        mRetypePasswordView.setVisibility(View.INVISIBLE);
        mButtonRegister.setText(R.string.st_la_Register);

        // Si el check est� pinchado recordar en las preferences
        PRC_RECORDAR_MAIL_PASSWORD();

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.st_la_Field_Required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < c_login_activity.LENGTH_PASSWORD) {
            mPasswordView.setError(getString(R.string.st_la_Invalid_Password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.st_la_Field_Required));
            focusView = mEmailView;
            cancel = true;
        } else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.st_la_Invalid_Email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.

            c_logging.getInstance().log(c_logging.LOG_INFO, "Lanzamos InitTask");
            // Anulado temporalmente
            // PRC_CARGAR_LOGIN_TASK(context, getString(R.string.st_la_Check_Connection_Thinking), getString(R.string.STR_OPERATION_LOGIN));
        }
    }

    //  Cargar Tarea Asincrona
    private void PRC_CARGAR_LOGIN_TASK (Context context, String str_modo, String modo) {
        // Lanzamos la tarea asíncrona
        // Lanzar la ejecución solo una vez
        if (_Task != null && _Task.getStatus() != AsyncTask.Status.FINISHED) {
            c_logging.getInstance().log(c_logging.LOG_INFO, "Cancelando CloseSessionTask (si existe antes)");
            _Task.cancel(true);
        }

        // ///////// TAREA ASINCRONA
        _Task = new LoginTask(c_login_activity.this, str_modo, modo);
        _Task.execute(this);

        try {
            this.ResultTask = _Task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }



    /*
     * TAREA LOGIN ASINCRONA
     */
    protected class LoginTask extends AsyncTask<Context, Integer, Integer> {

        Context						context;
        String						str_mesg;
        String						modo;
        ProgressDialog progress;

        private static final int	NETWORK_THINKING							= 0;

        private static final int	NETWORK_OK									= 1;
        private static final int	NETWORK_FAIL								= 2;
        private static final int	NETWORK_WIFI								= 3;
        private static final int	NETWORK_MOBILE								= 4;
        private static final int	NETWORK_UNKNOWN								= 5;

        private static final int	CONNECTING_TO_SERVER						= 6;
        private static final int	CONNECTING_TO_SERVER_OK						= 7;
        private static final int	CONNECTING_TO_SERVER_ERROR					= 8;
        private static final int	CONNECTING_TO_SERVER_FINISH					= 9;
        private static final int	HTTP_CONNECTING_ERROR						= 10;
        private static final int	CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT	= 11;
        private static final int	CONNECTING_TO_SERVER_ERROR_PROTOCOL			= 12;

        public LoginTask(Context context, String str_modo, String modo) {
            c_logging.getInstance().log(c_logging.LOG_INFO, "CONSTRUCTOR");
            this.context = context;
            this.str_mesg = str_modo;
            this.modo = modo;
        }

        // -- run intensive processes here
        // -- notice that the datatype of the first param in the class
        // definition matches the param passed to this method
        // -- and that the datatype of the last param in the class definition
        // matches the return type of this mehtod
        @Override
        protected Integer doInBackground(Context... params) {
            // -- on every iteration
            // -- runs a while loop that causes the thread to sleep for 50
            // milliseconds
            // -- publishes the progress - calls the onProgressUpdate handler
            // defined below
            // -- and increments the counter variable i by one
			/*
			 * int i = 0; while (i <= 50) { try { Thread.sleep(50); publishProgress(i); i++; } catch (Exception e) { Logging.getInstance().log( "[doInBackground]" +
			 * e.getMessage()); } }
			 */
            // Variable de retorno de la tarea as�ncrona
            // 1 si hay error
            // 0 si ha ido todo bien
            Integer return_code = 1;

            publishProgress(NETWORK_THINKING);

            // Comprobamos si hay conexion
            if (c_app_status.getInstance(this.context).isOnline(context)) {
                publishProgress(NETWORK_OK);
                c_logging.getInstance().log(c_logging.LOG_INFO, c_app_status.getInstance(this.context).getTypeStatus());

                // Comprobamos si es por wifi o mobil
                if ((c_connection_checking.getInstance(this.context).CheckWIFI()) || (c_connection_checking.getInstance(this.context).CheckMOBILE())) {
                    if (c_connection_checking.getInstance(this.context).CheckWIFI()) {
                        publishProgress(NETWORK_WIFI);
                    } else if (c_connection_checking.getInstance(this.context).CheckMOBILE()) {
                        publishProgress(NETWORK_MOBILE);
                    }
                    // Si llega aqu� todo va bien lanzamos la conexion http
                    // ****************************************************
                    try {
                        // Conexion http
                        // Probamos la conexion contra el servidor para ver si
                        // hay respuesta si nos devuelve 0 est� ok si nos
                        // devuelve otra cosa distinta de 0
                        // no hay conexi�n con el servidor.

                        publishProgress(CONNECTING_TO_SERVER);
                        c_constantes Constantes = new c_constantes();

                        c_http_post_get client = new c_http_post_get(Constantes.getAPI_PROTOCOL_HTTP() + Constantes.getAPI_IP(Constantes.getModoIP()) + Constantes.getAPI_URL_BASE()
                                + Constantes.getAPI_FILE(), Constantes.getAPI_CODIFICACION(), Constantes.getID_APP());

						/*
						 * Creamos el array con los datos de la operacion, username y password
						 */
                        ArrayList<NameValuePair> OpeUserPassw = new ArrayList<NameValuePair>();
                        OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_OPERATION), this.modo));

                        // Consultar las preferencias
                        Context context = getApplicationContext();
                        c_preferences appPrefs = new c_preferences(context);

                        // Parámetros
                        OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_USERNAME), appPrefs.getUsername(false)));
                        OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_PASSWORD), appPrefs.getPassword(false)));

                        try {
                            // Le pasamos el array con las operaciones y los
                            // datos del usuario
                            // La variable HTTP_USER_AGENT_APP_ANDROID es para
                            // que el php que detecta el movil lo ponga como
                            // APP_MOVIL
                            client.Execute(c_http_post_get.RequestMethod.POST, getString(R.string.HTTP_USER_AGENT_APP_ANDROID), OpeUserPassw, this.context, this.modo);
                            publishProgress(CONNECTING_TO_SERVER_OK);
                        } catch (SocketTimeoutException e) {
                            publishProgress(CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT);
                            c_logging.getInstance().log(c_logging.LOG_ERROR, e.toString());
                        } catch (ClientProtocolException e) {
                            publishProgress(CONNECTING_TO_SERVER_ERROR_PROTOCOL);
                            c_logging.getInstance().log(c_logging.LOG_ERROR, e.toString());
                        } catch (Exception e) {
                            c_logging.getInstance().log(c_logging.LOG_ERROR, e.toString());
                            publishProgress(CONNECTING_TO_SERVER_ERROR);
                        }

                        // Guardamos la respuesta de la petici�n HTTP.
                        ResponseHTTP = client.getResponse();
                        ResponseHTTP = ResponseHTTP.replaceAll("[\n\r]", "");
                        ResponseHTTP = ResponseHTTP.trim();
                        int responseCode = client.getResponseCode();
                        c_logging.getInstance().log(c_logging.LOG_INFO, "ResponseHTTP:  " + ResponseHTTP);
                        c_logging.getInstance().log(c_logging.LOG_INFO, "ResponseCODE:  " + responseCode);
                        // 200
                        if (responseCode == HttpStatus.SC_OK) {
                            publishProgress(CONNECTING_TO_SERVER_FINISH);
                            return_code = 0;
                        } else {
                            // Hago esto para que si hay alg�n error me lo
                            // devuelve en un Toast
                            publishProgress(responseCode);
                        }

                        // Fin conexion http
                    } catch (Exception e) {
                        c_logging.getInstance().log(c_logging.LOG_ERROR, e.toString());
                        publishProgress(HTTP_CONNECTING_ERROR);
                    }
                    // ****************************************************
                } else {
                    // ni wifi ni mobile
                    publishProgress(NETWORK_UNKNOWN);
                }
            } else {
                // sin conexion
                publishProgress(NETWORK_FAIL);
            }
            // Variable de retorno de la tarea as�ncrona
            // 1 -> si devuelve 1 es que no se ha realizado correctamente la
            // conexi�n. Despu�s tenemos que procesar el resultado json.
            return return_code;
        }

        // -- gets called just before thread begins
        @Override
        protected void onPreExecute() {
            c_logging.getInstance().log(c_logging.LOG_INFO, "INICIALIZANDO");
            super.onPreExecute();

            progress = new ProgressDialog(context);
            progress.setMessage(str_mesg);
            // set other progressbar attributes
            progress.show();
        }

        // -- called from the publish progress
        // -- notice that the datatype of the second param gets passed to this
        // method
        @Override
        protected void onProgressUpdate(Integer... code) {
            super.onProgressUpdate(code);

            String mensaje = "";
            switch (code[0]) {
                case NETWORK_OK:
                    mensaje = getString(R.string.st_la_Network_Ok);
                    break;
                case NETWORK_FAIL:
                    mensaje = getString(R.string.st_la_Network_Fail);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case NETWORK_WIFI:
                    mensaje = getString(R.string.st_la_Network_Ok) + " " + getString(R.string.st_la_WIFI);
                    break;
                case NETWORK_MOBILE:
                    mensaje = getString(R.string.st_la_Network_Ok) + " " + getString(R.string.st_la_MOBILE);
                    break;
                case NETWORK_UNKNOWN:
                    mensaje = getString(R.string.st_la_Network_Ok) + " " + getString(R.string.st_la_UNKNOWN);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case CONNECTING_TO_SERVER:
                    mensaje = getString(R.string.st_la_Connecting);
                    break;
                case CONNECTING_TO_SERVER_OK:
                    mensaje = getString(R.string.st_la_Connecting) + " " + getString(R.string.st_la_OK);
                    break;
                case CONNECTING_TO_SERVER_ERROR:
                    mensaje = getString(R.string.st_la_Connecting) + " " + getString(R.string.st_la_Refused);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case CONNECTING_TO_SERVER_FINISH:
                    // mensaje = getString(R.string.Connect_to_server) + " " +
                    // getString(R.string.Connect_to_server_ok);
                    // Toast.makeText(getApplicationContext(),
                    // getString(R.string.Http_Connect_Finish),
                    // Toast.LENGTH_LONG).show();
                    break;
                case HTTP_CONNECTING_ERROR:
                    mensaje = getString(R.string.st_la_Http_Connect_Error);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT:
                    mensaje = getString(R.string.st_la_Connect_Server_Error_Sockettimeout);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case CONNECTING_TO_SERVER_ERROR_PROTOCOL:
                    mensaje = getString(R.string.st_la_Connect_Server_Error_Protocol);
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
                case NETWORK_THINKING:
                    mensaje = getString(R.string.st_la_Check_Connection_Thinking);
                    break;
                default:
                    // Aqu� se va cuando hay mensajes 200, 300, 400, ... 500 ....
                    mensaje = getString(R.string.st_la_Connecting) + " - ErrorCode:" + code[0].toString();
                    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
                    break;
            }
            c_logging.getInstance().log(c_logging.LOG_INFO, "PROGRESS: (" + code[0].toString() + ")" + mensaje);
            progress.setMessage(mensaje);
            // Hacemos una pausa peque�a
            // SystemClock.sleep(100);

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled() {
            super.onCancelled();
            c_logging.getInstance().log(c_logging.LOG_INFO, "CANCELLED");
        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute(Integer result) {

            // result = 1 error
            // result = 0 ok
            c_logging.getInstance().log(c_logging.LOG_INFO, "1Result:  " + result + " ResponseHTTP: " + ResponseHTTP);

            // La conexion se ha realiado con �xito ahora hay que ver si el
            // login se ha hecho bien.
            if (result == 0) {
                // Comprobamos el json
                if ((ResponseHTTP == "") || (ResponseHTTP == null)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.st_la_Error) + ':' + this.modo, Toast.LENGTH_LONG).show();
                    c_logging.getInstance()
                            .log(c_logging.LOG_INFO, getString(R.string.st_la_Error) + ':' + this.modo + ' ' + " 2Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                } else {
                    if (this.modo == getString(R.string.STR_OPERATION_LOGIN)) {
                        c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.STR_OPERATION_LOGIN));
                        // login
                        // ResponseHTTP:
                        // -1 -> YA ESTOY LOGUEADO
                        // 0 -> ERROR EN PROCESO PROCESO_Login o SESSION_PROCESO_Login
                        // 3 -> USUARIO ACTIVO EN OTRO EQUIPO
                        // 4 -> USUARIO INACTIVO ANTES DE LOGUEARSE
                        // 5 -> USUARIO BLOQUEADO
                        // 6 -> USUARIO en PENDING_ACTIVATE
                        // El login solo se produce en los estados 3 o 4 en la web y
                        // en los estado 3, 4 y -1 en APP ya que si estoy logueado como u1
                        // por la web y me logueo por la APP me debe de dejar

                        if (ResponseHTTP.equals("0")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Error), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Error) + " 3Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        } else if (ResponseHTTP.equals("5")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Login_Blocked), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Login_Blocked) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        } else if (ResponseHTTP.equals("6")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Login_Pending_Activate), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Login_Pending_Activate) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);

                        } else if ((ResponseHTTP.equals("-1")) || (ResponseHTTP.equals("3")) || (ResponseHTTP.equals("4"))) {
                            c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.st_la_Login_Ok) + " 5Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                            Intent mainIntent = new Intent().setClass(c_login_activity.this, c_shopping_list.class);
                            startActivity(mainIntent);
                            finish();
                        } else {
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Error) + " 6Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        }
                    } else if (this.modo == getString(R.string.STR_OPERATION_REGISTER_USER)) {
                        // crar nuevo usuario
                        c_logging.getInstance().log(c_logging.LOG_INFO, getString(R.string.STR_OPERATION_REGISTER_USER));
                        // Al crear el nuevo usuario
                        // Result = 0 y ResponseHTTP = 0
                        // Si hay error
                        // Result = 0 y ResponseHTTP > 0, por ejemplo 1, es un usuario con ese nombre de usuario
                        if (ResponseHTTP.equals("0")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Register_Ok), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Register_Ok) + " 3Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        } else if (ResponseHTTP.equals("1")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Register_Fail), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Register_Fail) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        } else if (ResponseHTTP.equals("6")) {
                            Toast.makeText(getApplicationContext(), getString(R.string.st_la_Login_Pending_Activate), Toast.LENGTH_LONG).show();
                            c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Login_Pending_Activate) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
                        }
                    }
                }

            } else if (result == 1) {
                Toast.makeText(getApplicationContext(), getString(R.string.st_la_Error), Toast.LENGTH_LONG).show();
                c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Error) + " 7Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.st_la_Login_Unknown) + result.toString(), Toast.LENGTH_LONG).show();
                c_logging.getInstance().log(c_logging.LOG_ERROR, getString(R.string.st_la_Login_Unknown) + " 8Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
            }

            progress.dismiss();
        }

    }

	/*
	 * FIN TAREA LOGIN ASINCRONA
	 */



}
